<template>
  <div class="app-container">
    <div style="margin-bottom: 20px">
      <!--    文章标题-->
      <div class="title">文章标题</div>
      <el-input v-model="form.title" placeholder="请输入内容"></el-input>
    </div>
    <!--    Markdown描述-->
    <div style="margin-bottom:20px">
      <div class="title">Markdown描述</div>
      <Editor :options="configZH_CN" height="700px" :initialValue="form.editText" ref="toastuiEditor" />
    </div>
    <!--    文章描述-->
    <div style="margin-bottom: 20px">
      <div class="title">文章描述</div>
      <el-input type="textarea" :autosize="{ minRows: 10 }" placeholder="请输入内容" v-model="form.description">
      </el-input>
    </div>
    <!--    头图图片-->
    <UpLoad title="文章头图`（点击修改 / 可不选）" v-model="form.thumb" />
    <!--    选择 文章分类-->
    <div style="margin-top: 20px">
      <div class="title">给文章分个类</div>
      <el-select v-model="form.select" @change="forceUpdate_Handle" placeholder="请选择分类">
        <el-option v-for="item in blogTypeArr" :key="item.id" :label="item.name" :value='item.id'></el-option>
      </el-select>
    </div>
    <!--    提交按钮-->
    <el-button style="margin-top: 20px" type="primary" @click="addBlog_Handle">{{ btnText }}</el-button>
  </div>
</template>

<script>
import '@toast-ui/editor/dist/toastui-editor.css';
import { Editor } from '@toast-ui/vue-editor';
import UpLoad from "@/components/UpLoad/index.vue";
import { getBlogType_API } from "@/api/blogType";// 通过api拿文章分类
import * as pubBlog_API from "@/api/blog.js" // 调用发布文章 API
import '@toast-ui/editor/dist/i18n/zh-cn'//【markdown改成中文】
export default {
  props: ['mode'],
  data() {
    return {
      form: {
        title: '', //文章标题
        editText: '',//Markdown描述
        description: '',//文章描述
        thumb: '',//头图图片
        select: '',//选择分类 会填写到这里
      },
      blogTypeArr: [], //拿到的 分类文章 放进去
      configZH_CN: {
        language: 'zh-CN'
      },
      btnText: '添加文章',
    }
  },
  components: {
    Editor,
    UpLoad
  },
  async created() {
    const { data } = await getBlogType_API()
    // console.log("created开始拿数据：：", data)G
    console.log(this.$route, 'created开始就拿route的数据')
    // this.blogTypeArr.id = data.id
    this.blogTypeArr = data
    // console.log('我赋值给blogtypearrrrrrrrrr', this.blogTypeArr)
    localStorage.setItem('blogID', this.$route.params.id)
    if (window.location.reload) {
      const savedId = localStorage.getItem('blogID')
      console.log('blogID刷新了浏览器，重新拿id:::', savedId)
    }

    //   【进来时，根据id获取分类数据】
    if (this.mode === 'edit' && this.$route.params.id) {
      console.log(this.$route, '判断后的this.$route')
      this.btnText = '提交修改'
      this.id = this.$route.params.id
      if (this.id) {
        // console.log('在editBlog文件拿文章 编辑后ID：', this.$route.params.id)
        const { data } = await pubBlog_API.getBlog(this.id)
        console.log('通过getBlogAPI 参数id得到一篇文章:::', data)
        this.form = data
        // 【需要单独处理的 2个】
        this.$refs.toastuiEditor.invoke('setHTML', data.htmlContent)
        this.form.select = data.category ? data.category.id : ''
        console.log('这是回填后的formmmmmmmmmmmmmmmm', this.form)
      }
    }
  },
  methods: {
    //强制更新select
    forceUpdate_Handle() {
      this.$forceUpdate()
    },
    addBlog_Handle() {
      let html = this.$refs.toastuiEditor.invoke('getHTML');
      let markdown = this.$refs.toastuiEditor.invoke('getMarkdown');
      // console.log('添加文章', this.blogTypeArr)
      let blogObjInfo = {
        title: this.form.title,
        description: this.form.description,
        createDate: new Date().getTime(),//一串数字【】
        categoryId: this.form.select,
        toc: [],//我们不用管，markdown有
        htmlContent: html,
        markdownContent: markdown,
        thumb: this.form.thumb
      }
      console.log('拿到blogObjInfo信息：：', blogObjInfo)
      // if (blogObjInfo) {
      //   window.location.reload()
      // }
      if (blogObjInfo.title && blogObjInfo.description && blogObjInfo.categoryId && blogObjInfo.htmlContent) {
        if (this.mode === 'add') {
          //   有值才能提交【然后跳转到 文章列表】
          pubBlog_API.pubBlog(blogObjInfo).then(res => {
            this.$router.push('blogList')
            this.$message({
              message: '添加成功！',
              type: 'success'
            });
          })
        } else {
          pubBlog_API.editBlog({ id: this.form.id, data: blogObjInfo }).then(res => {
            this.$router.push('blogList')
            this.$message({
              message: '修改成功！',
              type: 'success'
            });
          })
        }

      } else {
        this.$message({
          message: '些许内容需填写！',
          type: 'warning'
        });
      }
    }
  },
}
</script>

<style scoped>
.title {
  font-weight: 100;
  margin-bottom: 10px;
}
</style>
